package com.sgzn.sgpay.service.tcp.receive.handler;

import com.sgzn.sgpay.service.tcp.receive.TcpReceiveCallHandlerTemplate;
import com.sgzn.sgpay.service.tcp.receive.modle.TcpReceiveCallRequest;
import com.sgzn.sgpay.service.tcp.receive.modle.response.TcpQueryTerminalBillExchangeResult;
import com.sgzn.sgpay.service.tcp.util.SgTcpUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 查询终端账目应答（兑币机） 处理器
 * @author huangsenguang
 * @version Id: TcpQueryTerminalBillExchangeHandler.java, v 0.1 2018/7/30 14:37 huangsenguang Exp $$
 */
@Service
@Slf4j
public class TcpQueryTerminalBillExchangeHandler extends TcpReceiveCallHandlerTemplate<TcpQueryTerminalBillExchangeResult> {
    /**
     * 协议总字符数
     */
    @Getter
    private final int protocolLength = 12;

    @Override
    public TcpQueryTerminalBillExchangeResult callInner(TcpReceiveCallRequest request) {
        String data = request.getData();
        TcpQueryTerminalBillExchangeResult result = new TcpQueryTerminalBillExchangeResult();
        result.setErrorCode(data.substring(0,2));
        result.setIncomeTotal(parse(data,2,10));
        result.setCloudPayTotal(parse(data,10,18));
        result.setLocalIncomeTotal(parse(data,18,26));
        result.setOutCoinTotal(parse(data, 26, 34));
        result.setPresentCoinTotal(parse(data, 34, 42));
        return result;
    }

    @Override
    protected void handleAfter(TcpReceiveCallRequest request, TcpQueryTerminalBillExchangeResult result) {
        //
    }

    @Override
    protected int getProtocolLength(TcpReceiveCallRequest request) {
        return this.protocolLength;
    }

    private int parse(String data, int beginIndex, int endIndex) {
        return Integer.parseInt(SgTcpUtil.sortTcp(data.substring(beginIndex, endIndex)), 16);
    }
}